"""
AI对话平台扩展ViewSet
包含消息、Token使用记录、模板和收藏等ViewSet
"""

from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema_view, extend_schema, OpenApiParameter
from drf_spectacular.types import OpenApiTypes
from django.db import models
from django.utils import timezone

from apps.common.responses import (
    ApiResponseMixin, ConfigurableActionMixin, 
    create_success_response_serializer,
    ValidationErrorResponseSerializer,
    NotFoundErrorResponseSerializer,
    ConflictErrorResponseSerializer
)

from .models import (
    AIMessage, TokenUsageLog, MessageTemplate, UserFavorite
)
from .serializers import (
    AIMessageSerializer, TokenUsageLogSerializer, 
    MessageTemplateSerializer, UserFavoriteSerializer,
    BatchOperationSerializer, TokenUsageStatsSerializer,
    ConversationExportSerializer, ConversationContextSerializer,
    ConversationContextResponseSerializer
)
from .context_manager import ConversationContextManager


@extend_schema_view(
    list=extend_schema(
        summary="获取AI消息列表",
        description="获取对话消息列表，支持分页、搜索和过滤",
        parameters=[
            OpenApiParameter(name='conversation', type=OpenApiTypes.INT, description='会话ID过滤'),
            OpenApiParameter(name='ai_role', type=OpenApiTypes.INT, description='AI角色ID过滤'),
        ],
    ),
    retrieve=extend_schema(
        summary="获取AI消息详情",
        responses={
            200: create_success_response_serializer(AIMessageSerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
    create=extend_schema(
        summary="创建AI消息",
        responses={
            201: create_success_response_serializer(AIMessageSerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新AI消息",
        responses={
            200: create_success_response_serializer(AIMessageSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
    destroy=extend_schema(
        summary="删除AI消息",
        responses={
            204: None,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class AIMessageViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ModelViewSet):
    """AI消息管理ViewSet"""
    serializer_class = AIMessageSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ['conversation', 'ai_role']
    search_fields = ['content']
    ordering_fields = ['created_at', 'updated_at', 'token_count']
    ordering = ['created_at']
    
    def get_queryset(self):
        """获取用户可访问的消息"""
        user = self.request.user
        if user.is_staff:
            return AIMessage.objects.all()
        
        # 用户只能访问自己会话的消息
        return AIMessage.objects.filter(conversation__owner=user)
    
    def perform_create(self, serializer):
        """创建时设置创建者"""
        serializer.save(created_by=self.request.user)
    
    def perform_update(self, serializer):
        """更新时设置更新者"""
        serializer.save(updated_by=self.request.user)


@extend_schema_view(
    list=extend_schema(
        summary="获取Token使用记录列表",
        description="获取Token使用记录列表，支持分页、搜索和过滤",
        parameters=[
            OpenApiParameter(name='user', type=OpenApiTypes.INT, description='用户ID过滤'),
            OpenApiParameter(name='ai_model', type=OpenApiTypes.INT, description='AI模型ID过滤'),
            OpenApiParameter(name='conversation', type=OpenApiTypes.INT, description='会话ID过滤'),
        ],
    ),
    retrieve=extend_schema(
        summary="获取Token使用记录详情",
        responses={
            200: create_success_response_serializer(TokenUsageLogSerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class TokenUsageLogViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ReadOnlyModelViewSet):
    """Token使用记录ViewSet（只读）"""
    serializer_class = TokenUsageLogSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ['user', 'ai_model', 'conversation']
    search_fields = ['conversation__title']
    ordering_fields = ['created_at', 'total_tokens']
    ordering = ['-created_at']
    
    def get_queryset(self):
        """获取用户的Token使用记录"""
        user = self.request.user
        if user.is_staff:
            return TokenUsageLog.objects.all()
        return TokenUsageLog.objects.filter(user=user)
    
    @extend_schema(
        summary="获取Token使用统计",
        parameters=[
            OpenApiParameter(name='period', type=OpenApiTypes.STR, description='统计周期: day/week/month'),
            OpenApiParameter(name='model_id', type=OpenApiTypes.INT, description='模型ID过滤'),
        ],
        responses={
            200: create_success_response_serializer(
                TokenUsageStatsSerializer, 
                "获取统计成功", 
                "Stats"
            ),
        }
    )
    @action(detail=False, methods=['get'])
    def stats(self, request):
        """获取Token使用统计"""
        period = request.query_params.get('period', 'month')
        model_id = request.query_params.get('model_id')
        
        # 计算时间范围
        now = timezone.now()
        if period == 'day':
            start_date = now - timezone.timedelta(days=1)
        elif period == 'week':
            start_date = now - timezone.timedelta(weeks=1)
        else:  # month
            start_date = now - timezone.timedelta(days=30)
        
        # 构建查询
        queryset = self.get_queryset().filter(created_at__gte=start_date)
        if model_id:
            queryset = queryset.filter(ai_model_id=model_id)
        
        # 计算统计数据
        stats = queryset.aggregate(
            total_tokens=models.Sum('total_tokens'),
            input_tokens=models.Sum('input_tokens'),
            output_tokens=models.Sum('output_tokens'),
        )
        
        # 按模型分组统计
        model_breakdown = {}
        model_stats = queryset.values('ai_model__name').annotate(
            total=models.Sum('total_tokens'),
            count=models.Count('id')
        )
        
        for item in model_stats:
            model_breakdown[item['ai_model__name']] = {
                'total_tokens': item['total'],
                'usage_count': item['count']
            }
        
        result = {
            'total_tokens': stats['total_tokens'] or 0,
            'input_tokens': stats['input_tokens'] or 0,
            'output_tokens': stats['output_tokens'] or 0,
            'total_cost': 0.0,  # TODO: 根据模型计算实际成本
            'period': period,
            'model_breakdown': model_breakdown
        }
        
        return self.success_response(result, "统计数据获取成功")


@extend_schema_view(
    list=extend_schema(
        summary="获取消息模板列表",
        description="获取用户的消息模板列表，支持分页、搜索和过滤",
        parameters=[
            OpenApiParameter(name='category', type=OpenApiTypes.STR, description='模板分类过滤'),
            OpenApiParameter(name='is_public', type=OpenApiTypes.BOOL, description='是否公开过滤'),
        ],
    ),
    retrieve=extend_schema(
        summary="获取消息模板详情",
        responses={
            200: create_success_response_serializer(MessageTemplateSerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
    create=extend_schema(
        summary="创建消息模板",
        responses={
            201: create_success_response_serializer(MessageTemplateSerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新消息模板",
        responses={
            200: create_success_response_serializer(MessageTemplateSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
    destroy=extend_schema(
        summary="删除消息模板",
        responses={
            204: None,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class MessageTemplateViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ModelViewSet):
    """消息模板管理ViewSet"""
    serializer_class = MessageTemplateSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ['category', 'is_public']
    search_fields = ['name', 'content']
    ordering_fields = ['created_at', 'updated_at', 'usage_count', 'name']
    ordering = ['-usage_count', '-created_at']
    
    def get_queryset(self):
        """获取用户可访问的模板"""
        user = self.request.user
        if user.is_staff:
            return MessageTemplate.objects.all()
        
        # 用户可以访问自己创建的模板和公开模板
        return MessageTemplate.objects.filter(
            models.Q(owner=user) | models.Q(is_public=True)
        )
    
    def perform_create(self, serializer):
        """创建时设置所有者"""
        serializer.save(
            owner=self.request.user,
            created_by=self.request.user
        )
    
    def perform_update(self, serializer):
        """更新时设置更新者"""
        serializer.save(updated_by=self.request.user)


@extend_schema_view(
    list=extend_schema(
        summary="获取用户收藏列表",
        description="获取用户的收藏列表，支持分页、搜索和过滤",
    ),
    retrieve=extend_schema(
        summary="获取用户收藏详情",
        responses={
            200: create_success_response_serializer(UserFavoriteSerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
    create=extend_schema(
        summary="创建用户收藏",
        responses={
            201: create_success_response_serializer(UserFavoriteSerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新用户收藏",
        responses={
            200: create_success_response_serializer(UserFavoriteSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
    destroy=extend_schema(
        summary="删除用户收藏",
        responses={
            204: None,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class UserFavoriteViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ModelViewSet):
    """用户收藏管理ViewSet"""
    serializer_class = UserFavoriteSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    search_fields = ['title', 'note']
    ordering_fields = ['created_at', 'updated_at']
    ordering = ['-created_at']
    
    def get_queryset(self):
        """获取用户的收藏"""
        user = self.request.user
        if user.is_staff:
            return UserFavorite.objects.all()
        return UserFavorite.objects.filter(owner=user)
    
    def perform_create(self, serializer):
        """创建时设置所有者"""
        serializer.save(
            owner=self.request.user,
            created_by=self.request.user
        )
    
    def perform_update(self, serializer):
        """更新时设置更新者"""
        serializer.save(updated_by=self.request.user)
